<template>
  <div class="ticket-detail-page">
    <div v-if="ticket && 'notFound' in ticket" style="color:red;font-size:18px;padding:48px;text-align:center;">未找到该工单</div>
    <div v-else-if="ticket">
      <div class="ticket-header">
        <h2>工单详情</h2>
        <el-tag :type="statusTagType(ticket.status)">{{ statusText(ticket.status) }}</el-tag>
        <el-tag :type="priorityTagType(ticket.priority)" style="margin-left:8px;">{{ priorityText(ticket.priority) }}</el-tag>
        <div class="ticket-actions">
          <el-button size="small" @click="onAssign" :disabled="ticket.status==='closed'">分配</el-button>
          <el-button size="small" @click="onCoStaff" :disabled="ticket.status==='closed'">协同处理人</el-button>
          <el-button size="small" type="danger" @click="onClose" :disabled="ticket.status==='closed'">关闭</el-button>
          <el-button size="small" @click="onRemark" :disabled="ticket.status==='closed'">添加备注</el-button>
          <el-button size="small" type="success" @click="onReopen" v-if="ticket.status==='closed'">重新打开</el-button>
        </div>
      </div>
      <TicketAssignDialog :visible="assignDialogVisible" :staffs="staffs" @update:visible="assignDialogVisible = $event" @confirm="handleAssign" />
      <TicketRemarkDialog :visible="remarkDialogVisible" @update:visible="remarkDialogVisible = $event" @confirm="handleRemark" />
      <TicketCoStaffDialog :visible="coStaffDialogVisible" :coStaffs="ticket.coHandlers" :staffs="staffs" @update:visible="coStaffDialogVisible = $event" @update:coStaffs="handleUpdateCoStaffs" />
      <el-descriptions :column="2" border style="margin-bottom: 18px;">
        <el-descriptions-item label="工单号">{{ ticket.id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ ticket.title }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ ticket.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ ticket.createTime }}</el-descriptions-item>
        <el-descriptions-item label="主处理人">{{ ticket.handler }}</el-descriptions-item>
        <el-descriptions-item label="协同处理人">
          <span v-if="ticket.coHandlers && ticket.coHandlers.length">{{ ticket.coHandlers.join('，') }}</span>
          <span v-else>—</span>
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <el-tag v-for="tag in ticket.tags" :key="tag" type="info" style="margin-right:4px;">{{ tag }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="自定义字段">
          <div v-if="ticket.customFields && ticket.customFields.length">
            <div v-for="f in ticket.customFields" :key="f.key">{{ f.key }}：{{ f.value }}</div>
          </div>
          <span v-else>—</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-card style="margin-bottom: 18px;">
        <template #header>工单内容</template>
        <div style="white-space: pre-line;">{{ ticket.content }}</div>
        <div v-if="ticket.attachments && ticket.attachments.length" style="margin-top:12px;">
          <b>附件：</b>
          <el-link v-for="a in ticket.attachments" :key="a.url" :href="a.url" target="_blank" style="margin-right:8px;">
            <el-icon v-if="a.type==='image'" style="vertical-align:middle;"><picture /></el-icon>
            {{ a.name }}
          </el-link>
        </div>
        <!-- 移除上传入口和添加附件按钮 -->
      </el-card>
      <el-card style="margin-bottom: 18px;">
        <template #header>处理流程</template>
        <TicketTimeline :timeline="ticket.timeline" />
      </el-card>
      <el-card>
        <template #header>评论区</template>
        <TicketComment :comments="ticket.comments" />
        <ImInputBar
          v-model:content="commentContent"
          v-model:attachments="commentAttachments"
          @send="onSendComment"
        />
      </el-card>
    </div>
    <div v-else style="text-align:center;padding:48px;">加载中...</div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { tickets } from '@/mock/mock-tickets'
import TicketTimeline from './components/TicketTimeline.vue'
import TicketComment from './components/TicketComment.vue'
import TicketAssignDialog from './components/TicketAssignDialog.vue'
import TicketRemarkDialog from './components/TicketRemarkDialog.vue'
import TicketCoStaffDialog from './components/TicketCoStaffDialog.vue'
import TicketAttachmentUpload from './components/TicketAttachmentUpload.vue'
import ImInputBar from './components/ImInputBar.vue'
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
const route = useRoute()
const ticketId = route.params.id as string
const ticketsRef = reactive([...tickets])
const ticket = computed(() => ticketsRef.find(t => t.id === ticketId) || { notFound: true })
const assignDialogVisible = ref(false)
const remarkDialogVisible = ref(false)
const coStaffDialogVisible = ref(false)
const commentContent = ref('')
const staffs = [
  { id: 'A', name: '客服A' },
  { id: 'B', name: '客服B' },
  { id: 'C', name: '客服C' },
  { id: 'D', name: '客服D' }
]
const newAttachments = ref<any[]>([])
const commentAttachments = ref<any[]>([])
function statusText(status: string) {
  if (status === 'pending') return '待处理'
  if (status === 'processing') return '处理中'
  if (status === 'done') return '已完成'
  if (status === 'closed') return '已关闭'
  return status
}
function statusTagType(status: string) {
  if (status === 'pending') return 'warning'
  if (status === 'processing') return 'primary'
  if (status === 'done') return 'success'
  if (status === 'closed') return 'info'
  return 'default'
}
function priorityText(priority: string) {
  if (priority === 'high') return '高'
  if (priority === 'medium') return '中'
  if (priority === 'low') return '低'
  return priority
}
function priorityTagType(priority: string) {
  if (priority === 'high') return 'danger'
  if (priority === 'medium') return 'warning'
  if (priority === 'low') return 'info'
  return 'default'
}
function onAssign() {
  assignDialogVisible.value = true
}
function onRemark() {
  remarkDialogVisible.value = true
}
function onClose() {
  if ('notFound' in ticket.value) return
  ticket.value.status = 'closed'
  ticket.value.timeline.unshift({ time: new Date().toLocaleString(), action: '关闭工单', operator: '系统', remark: '' })
  ElMessage.success('工单已关闭')
}
function handleAssign(staffId: string) {
  if ('notFound' in ticket.value) return
  ticket.value.handler = staffs.find(s => s.id === staffId)?.name || ''
  ticket.value.timeline.unshift({ time: new Date().toLocaleString(), action: '分配处理人', operator: '系统', remark: `分配给${ticket.value.handler}` })
  ElMessage.success('分配成功')
}
function handleRemark(remark: string) {
  if ('notFound' in ticket.value) return
  ticket.value.timeline.unshift({ time: new Date().toLocaleString(), action: '添加备注', operator: '系统', remark })
  ElMessage.success('备注已添加')
}
function onCoStaff() {
  coStaffDialogVisible.value = true
}
function handleUpdateCoStaffs(newCoStaffs: string[]) {
  if ('notFound' in ticket.value) return
  ticket.value.coHandlers = newCoStaffs
  ticket.value.timeline.unshift({ time: new Date().toLocaleString(), action: '协同处理人变更', operator: '系统', remark: `协同处理人：${newCoStaffs.join('，')}` })
  ElMessage.success('协同处理人已更新')
}
function onReopen() {
  if ('notFound' in ticket.value) return
  ticket.value.status = 'processing'
  ticket.value.timeline.unshift({ time: new Date().toLocaleString(), action: '重新打开工单', operator: '系统', remark: '' })
  ElMessage.success('工单已重新打开')
}
function onAddAttachment() {
  if ('notFound' in ticket.value) return
  ticket.value.attachments = [...(ticket.value.attachments || []), ...newAttachments.value]
  newAttachments.value = []
  ElMessage.success('附件已添加')
}
function onSendComment({ content, attachments }: { content: string, attachments: any[] }) {
  if ('notFound' in ticket.value) return
  if (!content.trim() && (!attachments || !attachments.length)) return
  // 明确类型，保证 comments 每项有 attachments 字段
  ticket.value.comments.push({ id: Date.now(), user: '当前用户', content, time: new Date().toLocaleString(), attachments: attachments || [] } as any)
  commentContent.value = ''
  commentAttachments.value = []
  ElMessage.success('评论已添加')
}
</script>

<style scoped>
.ticket-detail-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.ticket-header {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.ticket-header h2 {
  margin: 0 16px 0 0;
  color: #333;
}
.ticket-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}
</style>